<template>
  <el-container style="min-width: 100vw; min-height: 100vh; overflow-x: hidden;">
    <!-- 头部导航栏 -->
    <el-header style="padding: 0 0">
      <el-menu class="el-menu-demo" :default-active="tabIndex" mode="horizontal" :ellipsis="false" style="height:60px;align-items: center;background: rgba(51, 51, 51, 0.5);backdrop-filter: blur(5px);" @select="tabSelectMenu">
        <el-menu-item class="elMenuItemLogo">
          <div style="display: flex; align-items: center;">
            <img class="logo2" src="../public/favicon.ico" style="border-radius: 10px" alt="logo">
            <div class="logo" style="min-width: 200px;color: #fff;">摇光助手</div>
          </div>
        </el-menu-item>
        <div style="flex-grow: 1"/>
        <el-menu-item index="1" style="color: #fff;">首页</el-menu-item>
        <el-menu-item index="2" style="color: #fff;">在线配装</el-menu-item>
        <el-menu-item index="3" style="color: #fff;">配装大厅</el-menu-item>
        <el-button style="width: 100px;height: 100%" v-show="user.id===0" @click="my" link text type="danger">登录 / 注册</el-button>
        <el-dropdown style="width: 100px;height: 100%;justify-content: center" v-show="user.id !== 0">
          <el-button style="width: 100px;height: 100%" @click="my" link text type="success"> {{ user.username }}</el-button>
          <template #dropdown>
            <el-dropdown-menu style="justify-items: center">
              <el-dropdown-item @click="me">个人中心</el-dropdown-item>
              <el-dropdown-item @click="manager" :v-show="user.permissionLevel === 3">
                管理
              </el-dropdown-item>
              <el-dropdown-item @click="logout">退出</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-menu>
    </el-header>
    <!-- 主体内容区域 -->
    <el-main style="height: 88vh;flex-basis: auto;">
      <el-scrollbar style="width: 100%;height: 100%">
        <router-view/>
      </el-scrollbar>
<!--      <el-affix :offset="120" position="bottom" style="position: absolute;right: 50px;">-->
<!--        <el-popover :width="300" placement="left"  style="background: transparent">-->
<!--          <template #reference>-->
<!--            <el-row style="width: 50px;height: 50px;display: grid;">-->
<!--              <el-image src="wx_xcx.png" style="border-radius: 50px;width: 50px;height: 50px"/>-->
<!--            </el-row>-->
<!--          </template>-->
<!--          <template #default>-->
<!--            <el-row justify="center">-->
<!--              <el-image src="wx_xcx.png" style="border-radius: 50px"/>-->
<!--              <el-text style="margin-top: 30px">微信小程序</el-text>-->
<!--            </el-row>-->
<!--          </template>-->
<!--        </el-popover>-->
<!--      </el-affix>-->
    </el-main>
    <!-- 底部信息栏 -->
    <el-footer style="height: 5vh; background: rgba(51, 51, 51, 0.5); color: white; display: flex; align-items: center; justify-content: center; box-sizing: border-box;bottom: 0; width: 100%;">
      <a href="https://beian.miit.gov.cn" target="_blank" style="color: white; text-decoration: none;">京ICP备2025110281号</a>
    </el-footer>
  </el-container>

  <!--个人中心弹窗-->
  <el-dialog v-model="userInfoDialog" align-center width="700" :show-close="false" :before-close="()=>{}">
    <template #header>
      <el-row>
        <el-text size="large">个人中心</el-text>
      </el-row>
    </template>
    <el-form :model="user" label-position="right" style="margin-left: 30px;margin-right: 30px;margin-top: 15px">
      <el-form-item label="昵称：">
        <el-text v-show="!isEditNickName" style="width: 250px">{{ user.nickname }}</el-text>
        <el-input v-show="isEditNickName" v-model="user.nickname" placeholder="请输入昵称" type="text" maxlength="12" style="width: 250px"/>
        <el-row justify="start" style="flex: 1;margin-left: 30px">
          <el-button size="small" @click="editNickName">{{ isEditNickName ? '取消' : '修改' }}</el-button>
          <el-button size="small" type="success" v-show="isEditNickName" @click="submitNickName">提交</el-button>
        </el-row>
      </el-form-item>
      <el-form-item label="账号：">{{ user.username }}</el-form-item>
      <el-form-item label="邮箱：">{{ user.email }}</el-form-item>
      <el-form-item label="身份：">{{ user.permissionLevel === 3 ? "管理员" : "普通用户" }}</el-form-item>
      <el-form-item label="配装：">
        <el-tag
            v-show="meConfigList.length>0"
            v-for="tag in meConfigList"
            :key="tag"
            style="cursor: pointer;margin-right: 10px;margin-top: 10px"
            class="mx-1"
            size="large"
            closable
            :disable-transitions="true"
            @click="applyConfig(tag)"
            @close="delMeConfig(tag)">
          {{ tag.buildClass + "|" + tag.buildSchool + "|" + tag.buildName }}
        </el-tag>
        <el-row v-show="meConfigList.length===0">
          无
        </el-row>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="meCancel">关闭</el-button>
        <!--        <el-button type="primary" @click="meBtn">-->
        <!--          保存-->
        <!--        </el-button>-->
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="loginDialog" title="登录/注册" align-center width="400px" :show-close="false" :before-close="()=>{}" class="login-dialog">
    <el-form :model="loginFrom" label-position="top" style="padding: 20px 40px;">
      <el-form-item label="账号">
        <el-input
            v-model="loginFrom.username"
            placeholder="请输入账号"
            maxlength="18"
            minlength="8"
            :prefix-icon="User"
            class="custom-input"
        />
        <el-text type="danger" size="small" class="error-text">{{ usernameErr }}</el-text>
      </el-form-item>
      <el-form-item label="密码">
        <el-input
            v-model="loginFrom.password"
            placeholder="请输入密码"
            maxlength="18"
            minlength="8"
            type="password"
            show-password
            :prefix-icon="Lock"
            class="custom-input"
        />
        <el-text type="danger" size="small" class="error-text">{{ passwordErr }}</el-text>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="loginCancel" class="custom-button cancel-button">取消</el-button>
        <el-button type="primary" @click="loginBtn" class="custom-button login-button">登录</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage, ElMessageBox} from 'element-plus'
import {User, Lock} from '@element-plus/icons-vue'

export default {
  data() {
    return {
      user: JSON.parse(localStorage.getItem("user")) || {id: 0},
      tabIndex: sessionStorage.getItem("tabIndex") || 1,
      userInfoDialog: false,
      meConfigList: [],
      loginDialog: false,
      usernameErr: "",
      passwordErr: "",
      loginFrom: {
        username: "",
        password: "",
      },
      sWidth: 1800,
      isEditNickName: false
    }
  },

  methods: {
    tabSelectMenu(index) {
      switch (index) {
        case '1':
          this.$router.push({name: 'home'})
          break
        case '2':
          this.$router.push({name: 'equipment'})
          break
        case '3':
          this.$router.push({name: 'equipment_build_hall'})
          break
      }
      this.tabIndex = index
      sessionStorage.setItem("tabIndex", index)
    },
    my() {
      if (this.user.id === 0) {
        this.loginDialog = true;
      } else {

      }
    },
    async loginBtn() {
      let isValid = (str) => /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9]+$/.test(str)
      if (this.loginFrom.username.length < 8 || this.loginFrom.username.length > 18) {
        this.usernameErr = "账号长度必须在8-18位之间（包含8位，18位）"
        return;
      }
      if (!isValid(this.loginFrom.username)) {
        this.usernameErr = "账号格式只能为数字和字母的组合"
        return
      }
      if (this.loginFrom.password.length < 8 || this.loginFrom.password.length > 18) {
        this.passwordErr = "密码长度必须在8-18位之间（包含8位，18位）"
        return;
      }
      this.$http.post("/user/login", {
        username: this.loginFrom.username,
        password: this.loginFrom.password,
      }).then(res1 => {
        // permissionLevel '用户权限等级，1 - 普通用户，2 - 高级用户，3 - 管理员，默认为普通用户'
        console.log(res1)
        if (res1.data.code === 200) {
          let token = res1.headers['authorization']
          console.log(token)
          localStorage.setItem("token", token)
          this.user = res1.data.data
          localStorage.setItem("user", JSON.stringify(res1.data.data))
          this.loginDialog = false
          this.$emitter.emit('userInfo', res1.data.data);
        } else {
          ElMessage.error(res1.data.message);
        }
      }).catch(err1 => {
        console.log(err1)
        ElMessage.error(err1.data.message);
      })
    },
    loginCancel() {
      this.loginDialog = false;
      this.loginFrom.username = ""
      this.loginFrom.password = ""
      this.usernameErr = ""
      this.passwordErr = ""
    },
    //个人中心
    async me() {
      this.userInfoDialog = true
      this.$http.get('/equipment/builds/user/' + this.user.id).then(response => {
        if (response.data.code === 200) {
          if (response.data.data.length === 0) {
            this.meConfigList = []
          } else {
            this.meConfigList = response.data.data
          }
        } else {
          ElMessage.error(response.data.message);
        }
      }).catch(error => {
        if (error.status === 403) {
          ElMessage.error("登录状态失效，请重新登录");
        } else {
          ElMessage.error(error.message)
        }
      })

    },
    meCancel() {
      this.userInfoDialog = false
    },
    submitNickName() {
      this.http.post("/user/update", {
        id: this.user.id,
        nickname: this.user.nickname
      }).then(result => {
        if (result.data.code === 200) {
          this.isEditNickName = false
        } else {
          ElMessage.error(result.data.message);
        }
      }).catch(error => {
        ElMessage.error(error.message);
      })
    },
    applyConfig(data) {
      ElMessageBox.confirm("是否要应用配装【" + data.buildClass + "|" + data.buildSchool + "|" + data.buildName + "】？", "应用配装",
          {
            confirmButtonText: "应用",
            cancelButtonText: "取消",
            type: "warning",
          }
      ).then(() => {
        this.userInfoDialog = false
        this.$router.push({name: 'equipment'})
        setTimeout(() => {
          this.$emitter.emit('applyConfig', data, {once: true})
        }, 500)
      })
    },
    //删除个人配装
    delMeConfig(item) {
      ElMessageBox.confirm("是否要删除【" + item.buildClass + "|" + item.buildSchool + "|" + item.buildName + "】？", "删除",
          {
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            type: "warning",
          }
      ).then(() => {
        this.$http.post("equipment/builds/delete", {
          userId: this.user.id,
          id: item.id
        }).then(res => {
          if (res.data.code === 200) {
            this.me()
          } else {
            ElMessage.error(res.data.message);
          }
        }).catch(err => {
          ElMessage.error(err.message)
        })
      })
    },
    logout() {
      this.user = {id: 0}
      localStorage.removeItem("token")
      localStorage.removeItem("user")
      this.$emitter.emit('userInfo', {id: 0, username: '', phone: null, email: null, permissionLevel: 1})
      // this.$emitter.off('userInfo')
      //退出登录后回到首页
      this.$router.push({name: 'home'})

    },
    manager() {
      this.$router.push({name: "root_manage"})
    },
    editNickName() {
      this.isEditNickName = !this.isEditNickName
    }
  },
  created() {
    this.$emitter.on('login', (isLogin) => {
      if (isLogin) {
        this.loginDialog = true;
      }
    })
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.documentElement.clientWidth; //实时宽度
        window.screenHeight = document.documentElement.clientHeight; //实时高度
        this.screenWidth = window.screenWidth;
        this.screenHeight = window.screenHeight;
      })();
    };
  },

}
</script>

<style scoped>
.logo {
  font-weight: bold;
  margin-left: 40px;
}

.logo2 {
  height: 2rem; /* 设置 logo 高度 */
  margin-left: 30px;
}

/* 媒体查询，针对不同分辨率进行微调 */
@media (min-width: 1080px) {
  .logo {
    font-size: 20px;
  }
}

@media (min-width: 1920px) {
  .logo {
    font-size: 30px;
  }
}

@media (max-width: 2560px) {
  .logo {
    font-size: 30px;
  }
}

@media (max-width: 500px) {
  .logo {
    display: none;
  }

  .logo2 {
    margin-left: 10px;
  }
}


.elMenuItemLogo:hover {
  background: transparent !important;
}

.el-menu-item > a {
  color: white;
}

.el-menu-demo {
  border-bottom: none !important;
}

.el-footer > a:hover {
  background-color: transparent;
}

.login-dialog :deep(.el-dialog) {
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  text-align: center;
  background-color: var(--el-color-primary);
  color: white;
}

.login-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 20px;
  font-weight: bold;
}

.login-dialog :deep(.el-form-item__label) {
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.custom-input {
  margin-bottom: 5px;
}

.custom-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

.custom-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

.error-text {
  font-size: 12px;
  margin-top: 4px;
  display: block;
  min-height: 20px;
}

.dialog-footer {
  padding: 10px 20px 20px;
  text-align: center;
}

.custom-button {
  width: 120px;
  height: 40px;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.cancel-button {
  margin-right: 15px;
}

.cancel-button:hover {
  background-color: #f5f7fa;
}

.login-button {
  background: var(--el-color-primary);
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}
</style>